import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import ChanceViewAndEditStore from '../../stores/form/ChanceViewAndEditStore'
import { Form, RouteLayout, TabPage } from 'weaver-mobile-page';
import { Card, Icon, ActionSheet, ActivityIndicator, Tools, Modal, List } from 'weaver-mobile';
import CrmResult from '../card/CrmResult'
import NoRight from '../public/NoRight';

const ButtonGroup = RouteLayout.ButtonGroup;
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}

@withRouter
@observer
export default class ChanceViewAndEdit extends Component {
    constructor(props) {
        super(props);
        // console.log(props);
        this.state = {
            store: new ChanceViewAndEditStore(),
            sellChanceId: props.params.sellChanceId,
            sellChanceName: props.params.chanceName,
            customerId: props.params.customerId,
            canEdit: props.params.canEdit,
            isPro: props.params.isPro,
            emparams:props.emparams,
            span: [7, 1],
            selected: "",
            visible: false,
            tabs: [
                { title: props.params.chanceName, },
            ],
            popoverProps: {
                onSelect: this.handleSelect,
                onVisibleChange: this.handleVisibleChange,
            },
            tabProps: {
                swipeable: true,
                onChange: (tab) => {
                }
            }
        }
    }
    componentWillMount() {
        const { DoNew } = this.state.store;
        DoNew({ sellChanceId: this.state.sellChanceId, customerId: this.state.customerId }, this);
    }

    componentDidMount() {
        const store = this.state.store;
        store.doInit(this.state.emparams);
    }

    render() {
        const { viewForm, editForm, isFormInit, buttonProps, isViewForm, isEditForm, getViewForm, doSave, cancelEdit, initSuccessed, initFailedMsg } = this.state.store;
        const { span, visible, selected, btns, popoverProps, tabs, tabProps, canEdit } = this.state;
        //按钮组
        let buttonGroupData = [];
        buttonGroupData.push({
            key: 'clear',
            text: getLabel('201', '取消'),
            onClick: () => alert('', getLabel('390915', '确定要离开吗?'), [
                {
                    text: getLabel('201', '取消'),
                    onPress: () => { }
                },
                {
                    text: getLabel('83446', '确定'),
                    onPress: () => cancelEdit()
                },
            ])
        });
        buttonGroupData.push({
            key: 'submit',
            text: getLabel('615', '提交'),
            onClick: () => doSave(),
            type: 'primary',
            disabled: buttonProps.disabled,
            loading: buttonProps.loading
        });
        if (isFormInit) {
            if (initSuccessed) {
                if (isViewForm) {
                    let btns = [];
                    if (canEdit) {
                        btns = [
                            <Icon type="ellipsis" onClick={this.moreClick} />,
                        ];
                    }
                    return (
                        <div>
                            <TabPage
                                className="tab-page-example"
                                btns={btns}
                                span={span}
                                tabs={tabs}
                                tabProps={tabProps}
                                defaultTabBarProps={{ page: 4 }}
                                popover={false}
                                popoverProps={popoverProps}
                            />
                            <Form store={viewForm} className="crm_Form" />
                        </div>
                    );
                } else if (isEditForm) {
                    return (
                        <div className={"crm-form-main"}>
                            <div className="crm-form-content">
                                <Form style={{ height: '100%' }} >
                                    <List>
                                        {this.getFields()}
                                    </List>
                                </Form>
                            </div>
                            <ButtonGroup data={buttonGroupData} />
                        </div>
                    );
                }
            } else {
                return (
                    <NoRight />
                    // <div>
                    //     <CrmResult
                    //         message={initFailedMsg}
                    //     />
                    // </div>
                    
                    );
            }
        } else {
            return (
                <div className="crm-bg-loading"><ActivityIndicator text={"Loading..."} /></div>
            );
        }
    }
    moreClick = () => {
        const { getEditForm, doDelete } = this.state.store;
        const buttons = [//删除客户和编辑客户只有有编辑权限的人才能操作，查看权限打开后只有一个取消按钮，所以将权限判断放在【...】上
            {
                content: getLabel('501294', '编辑商机'),
            },

        ];
        if (!this.state.isPro) {
            buttons.push({ content: getLabel('501297', '删除商机'), })
        }
        buttons.push({ content: getLabel('201', '您确认要删除吗？'), })
        ActionSheet.showActionSheetWithOptions({
            options: buttons,
            cancelButtonIndex: buttons.length - 1,
            maskClosable: true,
            'data-seed': 'logId',
            wrapProps,
        }, (buttonIndex) => {
            if (buttonIndex === 0) {
                getEditForm();
            }
            if (!this.state.isPro) {
                if (buttonIndex === 1) {
                    // 删除商机
                    alert('', getLabel('83600', '您确认要删除吗？'), [
                        { text: getLabel('201', '取消'), onPress: () => { } },
                        { text: getLabel('83446', '确定'), onPress: () => { doDelete(); } },
                    ]);
                }
            }
        }
        )
    }
    getFields = () => {
        let { doChangeFormCondition, editForm } = this.state.store;
        const { conditioninfo, isInit } = editForm;
        const groups = [];
        if (isInit) {
            conditioninfo.forEach((group) => {
                const fields = [];
                group.items.forEach((field) => {
                    if (field.domkey.join('_') === 'customerid') {
                        if (editForm.formParams.customerid) {
                            doChangeFormCondition('comefromid', editForm.formParams.customerid);
                        }
                    }
                    fields.push(<Form.Item
                        key={field.domkey.join('_')}
                        form={editForm}
                        fieldConfig={field}
                        onChange={editForm.onChange}
                    />);
                });
                fields && groups.push(
                    // 分组
                    <div className='wm-form-group' key={group.title}>
                        <div className='wm-form-title' onClick={() => this.handldTogggle(group.title, !group.show)}>
                            {group.title}
                            <Icon className="am-icon" type={group.show ? 'up' : 'down'} />
                        </div>
                        <div className={`wm-form-list-wrap ${group.show ? 'show' : 'hide'}`}>
                            {fields}
                        </div>
                    </div>
                )
            });
        }
        return groups;
    }
    handldTogggle = (...arg) => {
        const { groupToggle } = this.props.chanceFormStore;
        groupToggle(...arg);
    }
    componentWillUnmount = () => {
        window.crmChance && window.crmChance.doInit();
    }
}